<?php

namespace backend\controllers;

use backend\models\File;
use backend\models\GameSource;
use common\helpers\Helper;
use SebastianBergmann\CodeCoverage\Report\PHP;
use yii\web\Controller;
use common\models\Region;
use yii\helpers\ArrayHelper;
use yii\web\Response;

/**
 * 公共调用处理
 */
class PublicController extends Controller
{

    public $layout = false;
    public $enableCsrfValidation = false;

    /**
     * ---------------------------------------
     * @inheritdoc
     * ---------------------------------------
     */
    public function actions()
    {
        return ArrayHelper::merge(parent::actions(), [
            /* 省市区联动 */
            /*'region' => [
                'class' => \kartik\depdrop\DepDropAction::className(),
                'outputCallback' => function ($id, $params) {
                    $region = Region::find()->where(['parent_id'=>$id])->orderBy('region_id ASC')->asArray()->all();
                    $_out = [];//var_dump($region);
                    foreach ($region as $value) {
                        $_tmp['id']   = $value['region_id'];
                        $_tmp['name'] = $value['region_name'];
                        $_out[] = $_tmp;
                    }
                    return $_out;
                },
                'selectedCallback' => function($id, $params){
                    return Yii::$app->getRequest()->get('sid');
                }
            ],*/
            /* ueditor文件上传 */
            /*'ueditor' => [
                'class' => 'common\actions\UEditorAction',
                'config' => Yii::$app->params['ueditorConfig'],
            ],*/
            /* 单图、多图上传 */
            'uploadImage' => [
                'class' => 'common\widgets\images\UploadAction',
            ],
            /* migration备份数据 */
            /*'backup' => [
                'class' => 'e282486518\migration\WebAction',
                'returnFormat' => 'json',
                'migrationPath' => '@console/migrations'
            ]*/
        ]);
    }

    /**
     * ---------------------------------------
     * 通用的404错误处理
     * @return string
     * ---------------------------------------
     */
    public function action404(){
        
        //渲染模板
        return $this->render('404');
    }

    public function uploadVideo(){

        $filename = Helper::buildGamePath().$_POST['name'];//确定上传的文件名

        if(!file_exists($filename)){

        }else{

        }
    }


    /**
     * 上传游戏原包
     * @return array
     */
    public function actionUploadApk()
    {
        if(\Yii::$app->request->isPost){
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $post = \Yii::$app->request->post();
            $count = (int) File::find()->where(['md5'=>$post['md5']])->count();
            if($count>0){
                return ['code'=>0,'message'=>'文件已经存在'];
            }
            $name = $post['file_name'];
            $path = Helper::buildGamePath();
            $file_path = $path.'/'.$name;

            if(!file_exists($file_path)){
                if(isset($post['last_upload']) && $post['last_upload']=='yes'){
                    move_uploaded_file($_FILES['apk']['tmp_name'],$file_path);
                    $finfo = finfo_open(FILEINFO_MIME_TYPE);
                    $mimetype = finfo_file($finfo, $file_path);
                    finfo_close($finfo);
                    if($mimetype!='application/java-archive'){
                        unlink($file_path);
                        return ['code'=>0,'message'=>'请上传apk游戏原包'];
                    }
                    $md5 = md5_file($file_path);
                    $sha1 = sha1_file($file_path);
                    if($post['md5']==$md5){
                        $file = new File();
                        $data['md5'] = $md5;
                        $data['sha1'] = $sha1;
                        $data['create_time'] = time();
                        $data['name'] = $name;
                        $data['ext'] = 'apk';
                        $data['mime'] = 'application/vnd.android';
                        $data['size'] = filesize($file_path);
                        $save_name = Helper::buildGameName();
                        $data['savepath'] = 'gamePackage/'.date('Ym').'/'.$save_name.'.apk';
                        $data['location'] = $path.'/'.$save_name;
                        $data['url'] = '/storage/'.$data['savepath'];
                        $file->setAttributes($data);
                        if($file->save()){
                            rename($file_path,$path.'/'.$save_name.'.apk');
                            return ['code'=>1,'fileInfo'=>$file->attributes];
                        }else{
                            unlink($file_path);
                            return ['code'=>0,'message'=>$file->getFirstError('md5')];
                        }
                    }

                }else{
                    move_uploaded_file($_FILES['apk']['tmp_name'],$file_path);
                    $finfo = finfo_open(FILEINFO_MIME_TYPE);
                    $mimetype = finfo_file($finfo, $file_path);
                    finfo_close($finfo);
                    if($mimetype!='application/java-archive'){
                        unlink($file_path);
                        return ['code'=>0,'message'=>'请上传apk游戏原包'];
                    }
                }

            }else{
                file_put_contents($file_path, file_get_contents($_FILES['apk']['tmp_name']), FILE_APPEND);
                if(isset($post['last_upload']) && $post['last_upload']=='yes'){
                    $md5 = md5_file($file_path);
                    $sha1 = sha1_file($file_path);
                    if($post['md5']==$md5){
                        $file = new File();
                        $data['md5'] = $md5;
                        $data['sha1'] = $sha1;
                        $data['create_time'] = time();
                        $data['name'] = $name;
                        $data['ext'] = 'apk';
                        $data['mime'] = 'application/vnd.android';
                        $data['size'] = filesize($file_path);
                        $save_name = Helper::buildGameName();
                        $data['savepath'] = 'gamePackage/'.date('Ym').'/'.$save_name.'.apk';
                        $data['location'] = $path.'/'.$save_name;
                        $data['url'] = '/storage/'.$data['savepath'];
                        $file->setAttributes($data);
                        if($file->save()){
                            rename($file_path,$path.'/'.$save_name.'.apk');
                            return ['code'=>1,'fileInfo'=>$file->attributes];
                        }else{
                            unlink($file_path);
                            return ['code'=>0,'message'=>$file->getFirstError('md5')];
                        }
                    }else{
                        unlink($file_path);
                        return ['code'=>0,'message'=>'可能是网络原因导致，md5校检不正确，请刷新后重新上传！','md5'=>$md5];
                    }
                }
            }
        }
    }



}
